package edu.ncsu.csc.ip.routing.dv.udp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import edu.ncsu.csc.ip.routing.dv.Node;
import edu.ncsu.csc.ip.routing.dv.RouteEntity;

/**
 * Class <code>distance_vector_udp</code>
 * 
 * distance_vector to comply with project description
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class distance_vector_udp {

	public static void main(String[] args) throws Exception {
		BufferedReader stdIn = new BufferedReader(new InputStreamReader(
				System.in));
		try {
			distance_vector_udp dv = new distance_vector_udp();
			RouterRemote router = dv.loadRouter(args[1], args[0]);
			router.initialize();
			System.out.println("Press Enter to Start . . .");
			stdIn.readLine();
			router.start();
			System.out.println("Started! Waiting for network to converge.");
			Thread.sleep(10000);
			router.localNode.printRoutingTable();
		} catch (Exception e) {
			System.err
					.println("USAGE:\n java distance_vector_remote <file name> <local host/ip>:<port>\n Example:\njava distance_vector_remote ./network/node1.txt 127.0.0.1:65421");
			e.printStackTrace();
		}

	}


	public RouterRemote loadRouter(String name, String fileName)
			throws IOException {

		RouterRemote router = new RouterRemote(new Node(name),
				Integer.parseInt(name.split(RouterRemote.IP_PORT_DELIM)[1]));

		File file;
		BufferedReader fileReader;
		file = new File(fileName);
		fileReader = new BufferedReader(new FileReader(file));
		String line;
		while ((line = fileReader.readLine()) != null) {
			String[] params = line.split(" ");
			double weight = Double.parseDouble(params[1]);
			Node neighbor = new Node(params[0]);
			router.localNode.neighborsMap.put(neighbor, new RouteEntity(
					neighbor, weight));
		}
		System.out.println("Neighbors Loaded For: " + name);
		fileReader.close();

		return router;
	}

}
